package com.woniuxy.school.dietary.order.websocket;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;


import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket的消息处理器
 */
@Component
public class MessageHandler implements WebSocketHandler {
    
    private static final Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap();
    @Autowired
    private StringRedisTemplate template;

    /**
     * 商家和服务器建立连接
     *
     * @param webSocketSession
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        System.out.println("连接成功，传入的参数对象是"+webSocketSession);
        //获取商家端id
        String storeId = webSocketSession.getUri().toString().split("=")[0];
        //将上传的商家id保存到map中
        webSocketSession.getAttributes().put("storeId", storeId);
        sessionMap.put(storeId, webSocketSession);
        System.out.println(sessionMap);
    }

    /**
     * 服务端收到客户端发来的消息
     *
     * @param webSocketSession
     * @param webSocketMessage
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

    }

    /**
     * 连接异常时执行
     *
     * @param webSocketSession
     * @param throwable
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
    }

    /**
     * 连接关闭
     *
     * @param webSocketSession
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        sessionMap.remove(webSocketSession.getAttributes().get("loginUserId"));
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
